//
//  SYRefreshControl.swift
//  SYWeibo
//
//  Created by Saya on 16/4/14.
//  Copyright © 2016年 黄金果. All rights reserved.
//

import UIKit
enum SYRefreshStatue: Int {
    case Normal = 0    // 普通状态
    case Pulling = 1    //准备刷新状态
    case Refreshing = 2 //刷新状态
}

private let RefreshViewHeight:CGFloat = 60

class SYRefreshControl: UIControl {
    
    //属性
    private var mySuper:UIScrollView?
    private var refreshState:SYRefreshStatue = .Normal {
        didSet{
            switch refreshState{
            case .Normal:
                textLb.text = "下拉刷新"
                arrorwImg.hidden = false
                indicator.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrorwImg.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.mySuper!.contentInset
                        inset.top = inset.top - RefreshViewHeight
                        self.mySuper?.contentInset = inset
                    })
                }
                
            case .Pulling:
                textLb.text = "准备刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrorwImg.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                textLb.text = "正在加载..."
                arrorwImg.hidden = true
                indicator.startAnimating()
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    guard let tempView = self.mySuper else{
                        print("error")
                        return
                    }
                    var inset = tempView.contentInset
                    inset.top = inset.top + RefreshViewHeight
                    self.mySuper?.contentInset = inset
                })
                
            }
        }
    }
    
    func endRefresh(){
        let delta = dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 2))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
        self.refreshState = .Normal
        }
    }
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshViewHeight , width: screenWidth, height: RefreshViewHeight)
        super.init(frame: rect)
        
        setUpUI()
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        mySuper = newSuperview as? UIScrollView
        
        mySuper?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        guard let mySuperView = mySuper else{
            print("no  super  view")
            return
        }
        let offset = mySuperView.contentOffset.y
//        print(offset)
        let targetOffset = -RefreshViewHeight - mySuperView.contentInset.top
        
        if mySuperView.dragging {
            if refreshState == .Pulling && offset > targetOffset {
                print("下拉刷新")
                refreshState = .Normal
            }else if  refreshState == .Normal && offset < targetOffset{
                print("准备刷新")
                refreshState = .Pulling
            }
        }else{
            
            if refreshState == .Pulling {
                print("正在加载...")
                refreshState = .Refreshing
            }
            
        }

    }
    
    
    private func setUpUI(){
        backgroundColor = UIColor.blueColor()
        
        addSubview(arrorwImg)
        addSubview(textLb)
        addSubview(indicator)
        
        arrorwImg.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        textLb.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrorwImg.snp_centerY)
            make.left.equalTo(arrorwImg.snp_right)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrorwImg.snp_center)
        }
        
    }
    
    private lazy var arrorwImg:UIImageView = {
        let iconImg = UIImageView()
        iconImg.image = UIImage(named: "tableview_pull_refresh")
        iconImg.sizeToFit()
        return iconImg
    }()
    
    private lazy var textLb:UILabel = UILabel(text: "下拉加载", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicator:UIActivityIndicatorView = UIActivityIndicatorView()

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit{
        mySuper?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
